package com.ikingtech.framework.sdk.web.support.agent;

import com.ikingtech.framework.sdk.context.exception.FrameworkException;
import com.ikingtech.framework.sdk.core.response.R;
import com.ikingtech.framework.sdk.core.support.LogHelper;
import com.ikingtech.framework.sdk.enums.common.FrameworkAgentTypeEnum;
import com.ikingtech.framework.sdk.utils.Tools;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Map;

/**
 * @author tie yan
 */
@Slf4j
@RequiredArgsConstructor
public class LoadBalanceFrameworkAgent implements FrameworkAgent {

    private final List<FrameworkAgentCaller> callers;

    private Map<FrameworkAgentTypeEnum, FrameworkAgentCaller> callerMap;

    @Override
    public R<Object> execute(FrameworkAgentTypeEnum agentType, Object data) {
        if (!this.callerMap.containsKey(agentType)) {
            LogHelper.info("LoadBalanceFrameworkAgent", "agent caller not found[agentType={}].", agentType);
            throw new FrameworkException("agent caller not found.");
        }
        return this.callerMap.get(agentType).call(data);
    }

    public void init() {
        this.callerMap = Tools.Coll.convertMap(this.callers, FrameworkAgentCaller::type);
        FrameworkAgentProxy.accept(this);
    }
}
